#!/usr/bin/python
# -*- coding: utf-8 -*-

import glob
import sys
import os
import re
import string
import pepe.p_txt.bigtxt as bt
import pepe.p_filesystem.basic as pfb

fslist = lambda x, y: pfb.fslist(x, patterns=y, recurse=True, return_folders=False)

n = '\x0D\x0A'

def main(inpath, filemask, rows2take="5"):
    ''' '''
    # add \ at the end of path if not present
    if inpath[-2:] <> '\x5C\x5C': inpath = inpath + '\x5C'

    files = fslist(inpath, filemask)

    # 2010-10-22_2257 vp
    ## using underscore instead dot because .# utilities 
    ## cut out everything after dot and then is not clear 
    ## whether utility was run on original file or on output
    ## of other .# utility that processed given file
    o = open('_tlh.#', 'wb')
    o.write('_\t_\t_' + n)
    
    for f in files:
    
        if f[-3:] in ('', ''):
            print f[-3:]
        else:
            print '\t', f
    
            lino = 0
    
            for line in bt.lines(f):
            
                line = re.sub('\x0D\x0A', '', line)
                line = re.sub('\x0D', '', line)
                line = re.sub('\x0A', '', line)
    
                lino += 1
                o.write("%s\t%s\t%s%s" % (line, str(lino), f, n))
    
                if str(lino) == rows2take:
                    break

    o.close()

if __name__ == "__main__":
    ''' '''
    #print sys.argv
    if len(sys.argv) == 3:
        main(inpath=sys.argv[1], filemask=sys.argv[2])
    elif len(sys.argv) == 4:
        main(inpath=sys.argv[1], filemask=sys.argv[2], rows2take=sys.argv[3])
    else:
        print """

        Traverse and List Headers (or Text List Headers) utility
        Take defined number lines from each file to distinguish text headers.
        
        tlh.py "\\server\path\directory" *.*
        tlh.py "\\server\path\directory" *.* 3

        """